/*
 * Copyright (C) 2019 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.xuexiang.xgithubclient.core.http;

import android.content.Context;

import com.tencent.mmkv.MMKV;
import com.xuexiang.xaop.annotation.IOThread;
import com.xuexiang.xaop.annotation.MainThread;
import com.xuexiang.xgithubclient.core.db.entity.AuthUser;
import com.xuexiang.xgithubclient.core.http.api.response.auth.BasicToken;
import com.xuexiang.xgithubclient.core.http.api.response.auth.User;
import com.xuexiang.xgithubclient.util.MMKVUtils;
import com.xuexiang.xgithubclient.util.XToastUtils;
import com.xuexiang.xormlite.XGithubDataBaseRepository;
import com.xuexiang.xormlite.db.DBService;
import com.xuexiang.xutil.common.StringUtils;

import java.sql.SQLException;
import java.util.Date;

/**
 * 账号管理
 *
 * @author xuexiang
 * @since 2019-07-01 11:25
 */
public final class AccountManager {

    private static volatile AccountManager sInstance = null;
    private static final String KEY_TOKEN = "com.xuexiang.xgithubclient.core.http.KEY_TOKEN";
    private static final String KEY_AUTHUSER = "com.xuexiang.xgithubclient.core.http.KEY_AUTHUSER";
    private static final String KEY_USER = "com.xuexiang.xgithubclient.core.http.KEY_USER";

    private String mToken;

    private AuthUser mAuthUser;
    private User mUser;

    private AccountManager() {

    }

    /**
     * 获取单例
     *
     * @return
     */
    public static AccountManager get() {
        if (sInstance == null) {
            synchronized (AccountManager.class) {
                if (sInstance == null) {
                    sInstance = new AccountManager();
                }
            }
        }
        return sInstance;
    }


    /**
     * 初始化Token信息
     */
    public static void init(Context context) {
        MMKVUtils.init(context);
        get().setToken(MMKV.defaultMMKV().decodeString(KEY_TOKEN, ""));
    }

    public static String getToken() {
        return "token " + get().mToken;
    }

    public static AuthUser getAuthUser() {
        return get().mAuthUser;
    }

    public static User getUser() {
        return get().mUser;
    }

    public AccountManager setToken(String token) {
        mToken = token;
        MMKV.defaultMMKV().encode(KEY_TOKEN, token);
        return this;
    }

    public AccountManager setAuthUser(AuthUser authUser) {
        mAuthUser = authUser;
        MMKV.defaultMMKV().encode(KEY_AUTHUSER, mAuthUser);
        return this;
    }

    public AccountManager setUser(User user) {
        mUser = user;
        MMKV.defaultMMKV().encode(KEY_USER, mUser);
        return this;
    }

    public AccountManager clearToken() {
        mToken = null;
        MMKV.defaultMMKV().remove(KEY_TOKEN);
        return this;
    }

    public static boolean hasToken() {
        return !StringUtils.isEmpty(get().mToken);
    }


    /**
     * 处理登陆成功
     *
     * @param basicToken
     * @param userInfo
     */
    @IOThread
    public void handleLoginSuccess(BasicToken basicToken, User userInfo) {
        DBService<AuthUser> dbService = XGithubDataBaseRepository.getInstance().getDataBase(AuthUser.class);
        try {
            dbService.executeSql("UPDATE auth_user SET selected = 0");
            dbService.executeSql("DELETE FROM auth_user WHERE loginId = '" + userInfo.getLogin() + "'");
        } catch (SQLException e) {
            e.printStackTrace();
        }

        AuthUser authUser = new AuthUser();
        String scope = StringUtils.listToString(basicToken.getScopes(), ",");
        Date date = new Date();
        authUser.setAccessToken(basicToken.getToken());
        authUser.setScope(scope);
        authUser.setAuthTime(date);
        //一年有效期
        authUser.setExpireIn(360 * 24 * 60 * 60);
        authUser.setSelected(true);
        authUser.setLoginId(userInfo.getLogin());
        authUser.setName(userInfo.getName());
        authUser.setAvatar(userInfo.getAvatarUrl());
        try {
            dbService.insert(authUser);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        setToken(basicToken.getToken());
        setAuthUser(authUser);
        setUser(userInfo);

        XToastUtils.success("登陆成功！");
    }

}
